package gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;


public class MenuPanel extends JPanel {
	
	private static final int DELAY = 1000;
	
	
	private MainPanel mainPanel;
	
	private JSpinner currentPuzzle;
	
	private int currentTime = 0;
	private Timer timer;
	private JLabel timeLabel;
	private JButton reset;

	
	public MenuPanel(MainPanel mainPanel) {
		this.mainPanel = mainPanel;
		
		initPanel();
	}
	
	private void initPanel() {
		add(new JLabel(Theme.emphasizedText("Puzzle: ")));
		currentPuzzle = createSpinner();
		add(currentPuzzle);
		
		JSeparator sep = new JSeparator(JSeparator.VERTICAL);
		sep.setPreferredSize(new Dimension(5, 20));
		add(sep);
		
		add(new JLabel(Theme.emphasizedText("Time: ")));
		timer = createTimer();
		timer.start();
		timeLabel = new JLabel(getTimeText());
		add(timeLabel);
		reset = createResetButton();
		add(reset);
		
	}
	
	private JSpinner createSpinner() {
		JSpinner spinner = new JSpinner(new SpinnerNumberModel(
				1, 
				1, 
				mainPanel.numberOfPuzzles(), 
				1
				));
		spinner.addChangeListener(new ChangeListener(){
			@Override
			public void stateChanged(ChangeEvent e) {
				
				int puzzle = (int) ((JSpinner) e.getSource()).getValue();
				mainPanel.setCurrent(puzzle);
				
			}
		});
		
		return spinner;
	}
	
	private Timer createTimer() {
		return new Timer(DELAY, new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				
				currentTime += DELAY;
				timeLabel.setText(getTimeText());
				
			}});
	}
	
	private JButton createResetButton() {
		JButton reset = new JButton(Theme.normalText("Reset"));
		reset.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				
				resetTime();
				
			}});
		
		return reset;
	}
	
	
	private String getTimeText() {
		int seconds = currentTime / 1000;
		
		return Theme.typewriterText(seconds + "s");
	}
	
	
	public void resetTime() {
		currentTime = 0;
		timeLabel.setText(getTimeText());
		timer.restart();
	}

}
